package com.bw.play.vm

import com.blankj.utilcode.util.GsonUtils
import com.bw.common.entity.CommendEntity
import com.bw.common.entity.DanmuEntity
import com.bw.common.vm.BaseViewModel
import com.bw.play.intent.PlayViewIntent
import com.bw.play.repo.PlayVideoRepository
import com.bw.play.state.PlayUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import javax.inject.Inject

@HiltViewModel
class PlayViewModel @Inject constructor(private val repository: PlayVideoRepository) :
    BaseViewModel<PlayViewIntent>() {

    private val _uiStateFlow = MutableStateFlow<PlayUiState>(PlayUiState.LoadEmpty)
    val uiStateFlow: StateFlow<PlayUiState> = _uiStateFlow.asStateFlow()

    override fun dispatchIntent(intent: PlayViewIntent) {
        when (intent) {
            is PlayViewIntent.LoadAuthorInfo -> getAuthorById(intent.userId)
            is PlayViewIntent.LoadRecommendSimpleVideo -> getRecommendSimpleVideo(
                intent.page,
                intent.pageSize
            )

            is PlayViewIntent.LoadSimpleVideoByChannelId -> getSimpleVideoByChannelId(
                intent.channelId,
                intent.page,
                intent.pageSize
            )

            is PlayViewIntent.LoadRecommendMultiVideo -> getRecommendMultiVideo(
                intent.page,
                intent.pageSize
            )

            is PlayViewIntent.LoadMultiVideoByTypeId -> getMultiVideoByTypeId(
                intent.typeId,
                intent.page,
                intent.pageSize
            )

            is PlayViewIntent.LoadVideoDanmuMsg -> getVideoDanmuMsg(
                intent.dataType,
                intent.itemId
            )

            is PlayViewIntent.PublishVideoComment -> publishComment(intent.content)
            is PlayViewIntent.PublishDanmuMsg -> publishDanmuMsg(intent.content)
            is PlayViewIntent.LoadCommentByUserId -> getCommentByUserId(
                intent.dataType,
                intent.itemId
            )
        }

    }

    /**
     *      * 获取视频作者信息
     *           */
    private fun getAuthorById(userId: String) {
        mViewModelScope.launch(mDispatcher) {
            repository.getAuthorById(userId).collectLatest {
                if (it != null) {
                    _uiStateFlow.emit(
                        PlayUiState.LoadAuthorSuccess(
                            it
                        )
                    )
                } else {
                    _uiStateFlow.emit(PlayUiState.LoadAuthorFail("获取当前视频作者信息失败！！"))
                }
            }
        }
    }

    /**
     *      * 获取首页推荐视频
     *           */
    private fun getRecommendSimpleVideo(page: Int, pageSize: Int) {
        mViewModelScope.launch(mDispatcher) {
            repository.getRecommendSimpleVideo(page, pageSize).collectLatest {
                if (it.isNotEmpty()) {
                    _uiStateFlow.emit(
                        PlayUiState.LoadSimpleVideoSuccess(
                            it
                        )
                    )
                } else {
                    _uiStateFlow.emit(PlayUiState.LoadSimpleVideoFail("获取当前视频失败！！"))
                }
            }
        }

    }

    /**
     *      * 获取首页分类下视频
     *           */
    private fun getSimpleVideoByChannelId(channelId: String, page: Int, pageSize: Int) {
        mViewModelScope.launch(mDispatcher) {
            repository.getSimpleVideoByChannelId(channelId, page, pageSize).collectLatest {
                if (it.isNotEmpty()) {
                    _uiStateFlow.emit(
                        PlayUiState.LoadSimpleVideoSuccess(
                            it
                        )
                    )
                } else {
                    _uiStateFlow.emit(PlayUiState.LoadSimpleVideoFail("获取当前视频失败！！"))
                }
            }
        }
    }

    /**
     *      * 获取放映厅推荐视频
     *           */
    private fun getRecommendMultiVideo(page: Int, pageSize: Int) {
        mViewModelScope.launch(mDispatcher) {
            repository.getRecommendMultiVideo(page, pageSize).collectLatest {
                if (it.isNotEmpty()) {
                    _uiStateFlow.emit(
                        PlayUiState.LoadMultiVideoSuccess(
                            it
                        )
                    )
                } else {
                    _uiStateFlow.emit(PlayUiState.LoadMultiVideoFail("获取当前放映厅视频失败！！"))
                }
            }
        }

    }

    /**
     *      * 获取放映厅分类下视频
     *           */
    private fun getMultiVideoByTypeId(typeId: Int, page: Int, pageSize: Int) {
        mViewModelScope.launch(mDispatcher) {
            repository.getMultiVideoByTypeId(typeId, page, pageSize).collectLatest {
                if (it.isNotEmpty()) {
                    _uiStateFlow.emit(
                        PlayUiState.LoadMultiVideoSuccess(
                            it
                        )
                    )
                } else {
                    _uiStateFlow.emit(PlayUiState.LoadMultiVideoFail("获取当前放映厅视频失败！！"))
                }
            }
        }
    }

    /**
     *      * 获取视频评论
     *           */
    private fun getCommentByUserId(dataType: Int, itemId: String) {
        mViewModelScope.launch(mDispatcher) {
            repository.getCommentByUserId(dataType, itemId).collectLatest {
                if (it.isNotEmpty()) {
                    _uiStateFlow.emit(
                        PlayUiState.LoadVideoCommentSuccess(
                            it
                        )
                    )
                } else {
                    _uiStateFlow.emit(PlayUiState.LoadVideoCommentFail("获取当前视频评论列表失败！！"))
                }
            }
        }

    }

    /**
     *      * 发送评论
     *           */
    private fun publishComment(str: String) {
        mViewModelScope.launch(mDispatcher) {
            //创建评论对象
            var commendEntity = CommendEntity(
                content = str,
                datatype = 0,
            )

            //封装成RequestBody对象
            var body: RequestBody = GsonUtils.toJson(commendEntity)
                .toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())

            //执行请求
            repository.publishComment(body).collectLatest {
                if (it != null) {
                    _uiStateFlow.emit(
                        PlayUiState.PublishVideoCommentSuccess(
                            it
                        )
                    )
                } else {
                    _uiStateFlow.emit(PlayUiState.PublishVideoCommentFail("发布视频评论失败！！"))
                }
            }
        }
    }

    /**
     *      * 发布弹幕
     *           */
    private fun publishDanmuMsg(danmu: String) {
        mViewModelScope.launch(mDispatcher) {
            //创建评论对象
            var danmuEntity = DanmuEntity(
                content = danmu,
                datatype = 0,
            )

            //封装成RequestBody对象
            var body: RequestBody = GsonUtils.toJson(danmuEntity)
                .toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())

            repository.publishDanmuMsg(body).collectLatest {
                if (it.isNotEmpty()) {
                    _uiStateFlow.emit(
                        PlayUiState.PublishVideoDanmuSuccess(
                            it
                        )
                    )
                } else {
                    _uiStateFlow.emit(PlayUiState.PublishVideoDanmuFail("发送视频弹幕失败！！"))
                }
            }
        }
    }

    /**
     *      * 获取视频弹幕
     *           */
    private fun getVideoDanmuMsg(dataType: Int, itemId: String) {
        mViewModelScope.launch(mDispatcher) {
            repository.getVideoDanmuMsg(dataType, itemId).collectLatest {
                if (it.isNotEmpty()) {
                    _uiStateFlow.emit(
                        PlayUiState.LoadVideoDanmuSuccess(
                            it
                        )
                    )
                } else {
                    _uiStateFlow.emit(PlayUiState.LoadVideoDanmuFail("获取当前视频弹幕失败！！"))
                }
            }
        }

    }


}